package cn.mujiankeji.mbrowser.数据.数据库

import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Insert
import androidx.room.Update
import androidx.room.Delete
import androidx.room.Query
import androidx.room.OnConflictStrategy
import kotlinx.coroutines.flow.Flow
import kotlinx.datetime.Clock

@Entity
data class DBHistory(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,

    @ColumnInfo(name = "title", defaultValue = "")
    var 标题: String = "",

    @ColumnInfo(name = "url", defaultValue = "")
    var 网址: String = "", // 如果是文件夹，此字段可为空或特定值

    @ColumnInfo(name = "icon", defaultValue = "NULL")
    var 图标: String? = null,

    @ColumnInfo(name = "time_create", defaultValue = "0")
    var 添加时间: Long = Clock.System.now().toEpochMilliseconds(), // 修改为 var 以便更新访问时间

    @ColumnInfo(name = "visit_count", defaultValue = "1") // 新增字段：访问次数
    var 访问次数: Int = 1
)

@Dao
interface DaoHistory{

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun 插入历史记录(历史记录: DBHistory): Long

    @Update
    suspend fun 更新历史记录(历史记录: DBHistory)

    @Query("SELECT * FROM DBHistory WHERE id = :id")
    fun 根据Id获取历史记录(id: Long): Flow<DBHistory?>

    @Query("SELECT * FROM DBHistory WHERE url = :url LIMIT 1")
    suspend fun 根据网址获取历史记录(url: String): DBHistory? // Suspend function for one-off check
    
    @Query("SELECT * FROM DBHistory WHERE url = :url LIMIT 1")
    fun 根据网址获取历史记录Flow(url: String): Flow<DBHistory?> // Flow version if needed

    @Query("SELECT * FROM DBHistory ORDER BY time_create DESC")
    fun 获取所有历史记录(): Flow<List<DBHistory>>

    @Query("SELECT * FROM DBHistory WHERE title LIKE '%' || :keyword || '%' OR url LIKE '%' || :keyword || '%' ORDER BY time_create DESC")
    fun 搜索历史记录(keyword: String): Flow<List<DBHistory>>

    @Delete
    suspend fun 删除历史记录(历史记录: DBHistory)
    
    @Query("DELETE FROM DBHistory WHERE id = :id")
    suspend fun 根据Id删除历史记录(id: Long)

    @Query("DELETE FROM DBHistory WHERE url = :url")
    suspend fun 根据网址删除历史记录(url: String)

    @Query("DELETE FROM DBHistory WHERE time_create < :beforeTime")
    suspend fun 删除指定时间之前的历史记录(beforeTime: Long)

    @Query("DELETE FROM DBHistory")
    suspend fun 清空所有历史记录()

    @Query("SELECT * FROM DBHistory ORDER BY time_create DESC LIMIT :count")
    fun 获取最近历史记录(count: Int): Flow<List<DBHistory>>

    @Query("SELECT * FROM DBHistory WHERE time_create >= :startTime AND time_create <= :endTime ORDER BY time_create DESC")
    fun 获取指定时间段历史记录(startTime: Long, endTime: Long): Flow<List<DBHistory>>

    // 获取热门网站 (根据访问次数字段排序)
    @Query("SELECT * FROM DBHistory ORDER BY visit_count DESC, time_create DESC LIMIT :count")
    fun 获取热门网站(count: Int): Flow<List<DBHistory>>
}